<template>
  <div class="container">
    <div class="flex items-center justify-between mb-6">
      <div>
        <h1 class="page-title text-2xl font-bold">加油记录</h1>
        <p class="text-gray-500">管理所有车辆的加油记录</p>
      </div>
      <div class="flex gap-2">
        <el-button type="primary" @click="handleAdd" class="btn-with-icon">
          <el-icon class="mr-1"><Plus /></el-icon>新增加油记录
        </el-button>
        <el-button type="success" @click="exportData" class="btn-with-icon">
          <el-icon class="mr-1"><Download /></el-icon>导出数据
        </el-button>
      </div>
    </div>
    
    <el-card shadow="hover" class="mb-6 card-with-hover">
      <div class="search-container flex flex-wrap items-center gap-4">
        <el-input
          v-model="queryParams.keyword"
          placeholder="搜索车牌号/驾驶员/加油站"
          prefix-icon="Search"
          clearable
          @clear="fetchData"
          @input="debounceSearch"
          style="width: 240px"
          class="search-input"
        />
        
        <el-select
          v-model="queryParams.fuelType"
          placeholder="油品类型"
          clearable
          @change="fetchData"
          style="width: 160px"
          class="fuel-type-select"
        >
          <el-option 
            v-for="item in FUEL_TYPE_OPTIONS"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="fetchData"
          style="width: 300px"
          class="date-picker"
        />
        
        <div class="flex gap-2">
          <el-button type="primary" @click="fetchData" :loading="loading" class="search-btn">
            <el-icon class="mr-1"><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery" class="reset-btn">
            <el-icon class="mr-1"><Refresh /></el-icon>重置
          </el-button>
        </div>
      </div>
    </el-card>
    
    <el-card shadow="hover" class="overflow-hidden card-with-hover">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :header-cell-class-name="'bg-gray-100 dark:bg-gray-700'"
        class="custom-table"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="plateNumber" label="车牌号" width="120" />
        <el-table-column prop="driver" label="驾驶员" width="100" />
        <el-table-column prop="fuelDate" label="加油时间" width="160" />
        <el-table-column prop="fuelType" label="油品" width="100" />
        <el-table-column prop="volume" label="加油量(L)" width="100" align="right">
          <template #default="{ row }">
            {{ row.volume.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价(元/L)" width="100" align="right">
          <template #default="{ row }">
            {{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额(元)" width="100" align="right">
          <template #default="{ row }">
            {{ row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stationName" label="加油站" width="150" />
        <el-table-column prop="currentMileage" label="当前里程" width="100" align="right" />
        <el-table-column prop="cardNumber" label="加油卡号" width="150" />
        <el-table-column prop="remark" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <div class="flex gap-1">
              <el-button 
                type="primary" 
                size="small"
                @click="handleEdit(row)"
                class="edit-btn"
              >
                <el-icon class="mr-1"><Edit /></el-icon>编辑
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="handleDelete(row)"
                class="delete-btn"
              >
                <el-icon class="mr-1"><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container mt-4 flex justify-center">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="DEFAULT_PAGE_SIZES"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="custom-pagination"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增加油记录' : '编辑加油记录'"
      width="500px"
      destroy-on-close
      class="custom-dialog"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        label-position="right"
        class="form-container"
      >
        <el-form-item label="车牌号" prop="plateNumber">
          <el-select
            v-model="form.plateNumber"
            placeholder="请选择车牌号"
            filterable
            clearable
            class="w-full"
          >
            <el-option
              v-for="item in vehicleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="驾驶员" prop="driver">
          <el-select
            v-model="form.driver"
            placeholder="请选择驾驶员"
            filterable
            clearable
            class="w-full"
          >
            <el-option
              v-for="item in driverOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="加油时间" prop="fuelDate">
          <el-date-picker
            v-model="form.fuelDate"
            type="datetime"
            placeholder="请选择加油时间"
            class="w-full"
          />
        </el-form-item>
        
        <el-form-item label="油品" prop="fuelType">
          <el-select
            v-model="form.fuelType"
            placeholder="请选择油品"
            class="w-full"
          >
            <el-option
              v-for="item in FUEL_TYPE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="加油量(L)" prop="volume">
          <el-input-number 
            v-model="form.volume" 
            :min="0" 
            :step="0.01"
            :precision="2"
            class="w-full"
            @change="calculateAmount"
          />
        </el-form-item>
        
        <el-form-item label="单价(元/L)" prop="price">
          <el-input-number 
            v-model="form.price" 
            :min="0" 
            :step="0.01"
            :precision="2"
            class="w-full"
            @change="calculateAmount"
          />
        </el-form-item>
        
        <el-form-item label="金额(元)" prop="amount">
          <el-input-number 
            v-model="form.amount" 
            :min="0" 
            :step="0.01"
            :precision="2"
            class="w-full"
            disabled
          />
        </el-form-item>
        
        <el-form-item label="加油站" prop="stationName">
          <el-input v-model="form.stationName" placeholder="请输入加油站名称" />
        </el-form-item>
        
        <el-form-item label="当前里程" prop="currentMileage">
          <el-input-number 
            v-model="form.currentMileage" 
            :min="0" 
            :step="0.1"
            :precision="1"
            class="w-full"
          />
        </el-form-item>
        
        <el-form-item label="加油卡号" prop="cardNumber">
          <el-select
            v-model="form.cardNumber"
            placeholder="请选择加油卡"
            filterable
            clearable
            class="w-full"
          >
            <el-option
              v-for="item in fuelCardOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, Download, Search, Refresh, Edit, Delete, 
  Money, Calendar, LocationFilled, Van
} from '@element-plus/icons-vue'
import { fuelUsageApi, vehicleApi, driverApi, fuelCardApi } from '@/api'
import { DEFAULT_PAGE_SIZE, DEFAULT_PAGE_SIZES, FUEL_TYPE, FUEL_TYPE_OPTIONS } from '@/utils/constants'
import { fuelUsageRules } from '@/utils/formRules'

export default {
  name: 'FuelUsagePage',
  components: {
    Plus,
    Download,
    Search,
    Refresh,
    Edit,
    Delete,
    Money,
    Calendar,
    LocationFilled,
    Van
  },
  setup() {
    // 表格数据
    const tableData = ref([])
    const loading = ref(false)
    
    // 分页
    const currentPage = ref(1)
    const pageSize = ref(DEFAULT_PAGE_SIZE)
    const total = ref(0)
    
    // 查询参数
    const queryParams = reactive({
      fuelType: '',
      dateRange: [],
      keyword: ''
    })
    
    // 下拉选项
    const vehicleOptions = ref([])
    const driverOptions = ref([])
    const fuelCardOptions = ref([])
    
    // 对话框
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const formRef = ref(null)
    const submitLoading = ref(false)
    
    // 表单
    const defaultForm = {
      id: undefined,
      plateNumber: '',
      driver: '',
      fuelDate: '',
      fuelType: '',
      volume: 0,
      price: 0,
      amount: 0,
      stationName: '',
      currentMileage: 0,
      cardNumber: '',
      remark: ''
    }
    
    const form = reactive({...defaultForm})
    
    // 表单验证规则
    const rules = fuelUsageRules
    
    // 获取选项
    const fetchOptions = async () => {
      try {
        // 获取车辆
        const vehicleRes = await vehicleApi.getVehicleList({ status: 1 })
        vehicleOptions.value = vehicleRes.map(item => ({
          label: `${item.plateNumber} (${item.brand})`,
          value: item.plateNumber
        }))
        
        // 获取驾驶员
        const driverRes = await driverApi.getDriverList({ status: 1 })
        driverOptions.value = driverRes.map(item => ({
          label: `${item.name} (${item.department})`,
          value: item.name
        }))
        
        // 获取加油卡
        const fuelCardRes = await fuelCardApi.getFuelCardList({ status: 1 })
        fuelCardOptions.value = fuelCardRes.map(item => ({
          label: `${item.cardNumber} (余额: ${item.balance})`,
          value: item.cardNumber
        }))
      } catch (error) {
        console.error('获取选项失败', error)
      }
    }
    
    // 获取加油记录列表
    const fetchData = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          fuelType: queryParams.fuelType || undefined,
          keyword: queryParams.keyword || undefined,
          startDate: queryParams.dateRange && queryParams.dateRange[0],
          endDate: queryParams.dateRange && queryParams.dateRange[1]
        }
        
        const { total: totalCount, list } = await fuelUsageApi.getFuelList(params)
        
        tableData.value = list
        total.value = totalCount
      } catch (error) {
        console.error('获取加油记录失败', error)
        ElMessage.error('获取加油记录失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = (keyword) => {
      queryParams.keyword = keyword
      currentPage.value = 1
      fetchData()
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pageSize.value = size
      fetchData()
    }
    
    // 分页页码变化
    const handleCurrentChange = (page) => {
      currentPage.value = page
      fetchData()
    }
    
    // 计算金额
    const calculateAmount = () => {
      form.amount = Number((form.volume * form.price).toFixed(2))
    }
    
    // 添加加油记录
    const handleAdd = () => {
      dialogType.value = 'add'
      Object.assign(form, defaultForm)
      form.fuelDate = new Date()
      
      dialogVisible.value = true
      
      // 重置表单验证
      if (formRef.value) {
        formRef.value.resetFields()
      }
    }
    
    // 编辑加油记录
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      
      Object.assign(form, {
        ...defaultForm,
        ...row
      })
      
      dialogVisible.value = true
    }
    
    // 删除加油记录
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        '确定要删除该加油记录吗？此操作不可恢复',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await fuelUsageApi.deleteFuel(row.id)
          ElMessage.success('删除成功')
          fetchData()
        } catch (error) {
          console.error('删除失败', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {})
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (!valid) return
        
        submitLoading.value = true
        try {
          if (dialogType.value === 'add') {
            // 添加加油记录
            await fuelUsageApi.addFuel(form)
            ElMessage.success('添加成功')
          } else if (dialogType.value === 'edit') {
            // 编辑加油记录
            await fuelUsageApi.updateFuel(form)
            ElMessage.success('更新成功')
          }
          
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          console.error('操作失败', error)
          ElMessage.error('操作失败')
        } finally {
          submitLoading.value = false
        }
      })
    }
    
    // 导出数据
    const exportData = () => {
      ElMessage({
        message: '数据导出成功，请在下载中心查看',
        type: 'success',
        duration: 2000
      })
      // 实际项目中应调用导出API
      // window.location.href = '/api/fuel-usage/export'
    }
    
    // 重置查询
    const resetQuery = () => {
      queryParams.keyword = ''
      queryParams.fuelType = ''
      queryParams.dateRange = null
      fetchData()
    }
    
    // 防抖搜索
    let searchTimeout = null
    const debounceSearch = () => {
      if (searchTimeout) {
        clearTimeout(searchTimeout)
      }
      searchTimeout = setTimeout(() => {
        fetchData()
      }, 500)
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchData()
      fetchOptions()
    })
    
    return {
      tableData,
      loading,
      currentPage,
      pageSize,
      total,
      queryParams,
      dialogVisible,
      dialogType,
      formRef,
      form,
      rules,
      submitLoading,
      vehicleOptions,
      driverOptions,
      fuelCardOptions,
      DEFAULT_PAGE_SIZES,
      FUEL_TYPE_OPTIONS,
      fetchData,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      calculateAmount,
      handleAdd,
      handleEdit,
      handleDelete,
      submitForm,
      exportData,
      resetQuery,
      debounceSearch
    }
  }
}
</script>

<style scoped>
.el-table :deep(.el-table__header) th {
  font-weight: 600;
}

.el-card {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border-radius: 8px;
}

.card-with-hover:hover {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px);
}

.page-title {
  position: relative;
  margin-bottom: 4px;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: -4px;
  left: 0;
  width: 40px;
  height: 3px;
  background-color: var(--el-color-primary);
  border-radius: 3px;
}

.btn-with-icon {
  display: flex;
  align-items: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.btn-with-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.search-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}

.search-input, .fuel-type-select, .date-picker {
  transition: all 0.3s;
}

.search-input:focus, .fuel-type-select:focus, .date-picker:focus {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-pagination {
  margin-top: 16px;
}

.custom-dialog :deep(.el-dialog__header) {
  border-bottom: 1px solid #eee;
  padding: 16px 20px;
}

.custom-dialog :deep(.el-dialog__footer) {
  border-top: 1px solid #eee;
  padding: 16px 20px;
}

/* 编辑和删除按钮样式 */
.edit-btn, .delete-btn {
  transition: all 0.3s;
}

.edit-btn:hover, .delete-btn:hover {
  transform: translateY(-2px);
}

.edit-btn:hover {
  background-color: var(--el-color-primary-light-3);
}

.delete-btn:hover {
  background-color: var(--el-color-danger-light-3);
}

/* 表格行样式 */
:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 搜索和重置按钮样式 */
.search-btn, .reset-btn {
  transition: all 0.3s;
}

.search-btn:hover, .reset-btn:hover {
  transform: translateY(-2px);
}

/* 暗黑模式适配 */
:deep(.dark-theme .el-table) {
  --el-table-border-color: var(--border-color);
  --el-table-header-bg-color: var(--bg-color);
}

/* 搜索和过滤组件样式 */
.el-input, .el-select, .el-date-picker {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}
</style> 